﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using hotel.Win.Common;
using hotel.DAL;
using hotel.Win.BaseData;
using hotel.Win.Subscribe;
using hotel.Common;
using hotel.MyUserControl;
using System.Threading;
using hotel.Win.Systems;
namespace hotel.Win
{
    public partial class MainControl
    {

        private TableLayoutPanel canvasThread;
        private List<ROOM> housesThread;
        private void CreateRoomStateThread(TableLayoutPanel canvas, List<ROOM> houses)
        {            
            if (AllRoom == null)
                AllRoom = new Dictionary<string, ucRoom>();
            else
                AllRoom.Clear();
            //填充到panel
            canvas.Controls.Clear();
            canvas.ColumnStyles.Clear();
            canvas.RowStyles.Clear();           
            houses.OrderBy(p => p.ID);
            if (houses.Count() == 0)
                return;
            int roomMaxWidth = UcRoomSet.GetUcRoomSet.Width;
            int roomMaxHeight = UcRoomSet.GetUcRoomSet.Height;
            canvas.SuspendLayout();
            //本栋楼，单层最大房间数
            var maxRoomCnt = (from q in houses
                              group q by q.LC into g
                              select g).Max(p => p.Count());

            int maxFloorCnt = houses.Max(p => p.LC); //最大楼层

            canvas.ColumnCount = maxRoomCnt + 2;//[0,0]为标题栏
            //创建横向（列）房间数
            var hcol = new ColumnStyle(SizeType.Absolute, 40);//与CreateRowControl,的width相同
            canvas.ColumnStyles.Add(hcol);
            for (int i = 0; i < maxRoomCnt +1; i++)
            {
                var colstyle = new ColumnStyle(SizeType.Absolute, roomMaxWidth);
                canvas.ColumnStyles.Add(colstyle);
            }
            //行，楼层
            canvas.RowCount = maxFloorCnt + 2;
            canvas.RowStyles.Add(new RowStyle(SizeType.Absolute, 23));//列标题栏
            for (int i = 0; i < maxFloorCnt+1; i++)
            {
                canvas.RowStyles.Add(new RowStyle(SizeType.Absolute, roomMaxHeight));
            }
            //canvas.Size = new Size(maxRoomCnt * (roomMaxWidth + 2) + 26, maxFloorCnt * (roomMaxHeight + 2) + 23);
            for (int i = 0; i < maxRoomCnt; i++)
            {
                canvas.Controls.Add(CreateColumnControl((i + 1).ToString().PadLeft(2, '0')), i + 1, 0);
            }           

            for (int i = maxFloorCnt; i > 0; i--)
            {
                canvas.Controls.Add(CreateRowControl((i).ToString().PadLeft(2, '0') + "/F"), 0, maxFloorCnt - i + 1);
            }
            canvasThread = canvas;
            housesThread = houses;
            canvasThread.Visible = false;
            Thread myThread = new Thread(new ParameterizedThreadStart(this.CreateBuildingThread));          
            myThread.IsBackground = true;
            myThread.Start(maxFloorCnt);

        }

        private void ShowCreateRoomProgress(ThreadData data)
        {
            if (this.InvokeRequired)
            {
                Action<ThreadData> ac = (p1) => ShowCreateRoomProgress(p1);
                this.Invoke(ac, new object[] { data });
            }
            else
            {
                lbmsg.Text = "正在创建房间：" + data.ucroom.Room.ID;
                if (progressBar1.Maximum != data.rooms)
                    progressBar1.Maximum = data.rooms;
                progressBar1.Value = data.index;
                canvasThread.Controls.Add(data.ucroom, data.column, data.maxFloorCnt - data.floor + 1);
                AllRoom.Add(data.ucroom.Room.ID, data.ucroom);
                if (progressBar1.Value >= progressBar1.Maximum)
                {
                    canvasThread.ResumeLayout();
                    canvasThread.Visible = true;
                    groupProgress.Visible = false;
                    ComputerRoomStatusLable();
                }
            }
        }

        private void CreateBuildingThread(object maxFloorCntobj)
        {
            int maxFloorCnt = Convert.ToInt32(maxFloorCntobj);
            //创建房间
            int lc = 0;
            int roomCount = housesThread.Count();
            int index = 0;
            Font myFont = new Font("宋体", (float)UcRoomSet.GetUcRoomSet.FontSize, UcRoomSet.GetUcRoomSet.FontBold ? System.Drawing.FontStyle.Bold : System.Drawing.FontStyle.Regular);
            int roomWidth = UcRoomSet.GetUcRoomSet.Width;
            int roomHeight = UcRoomSet.GetUcRoomSet.Height;
            for (int f = maxFloorCnt; f > 0; f--)
            {
                int col = 1;
                lc = f;
                foreach (var h in housesThread.Where(p => p.LC == lc).OrderBy(p => p.ID))
                {
                    var uc = new ucRoom(h);
                    uc.DoubleClickCallBack = RoomDoubleClickCallBack;
                    uc.DragDropCallBack = RoomDragDropCallBack;
                    uc.ClickCallBack = RoomClickCallBack;
                    uc.SetContextMenu(this.contextMenuRoom);
                    uc.Width = roomWidth;
                    uc.Height = roomHeight;
                    uc.LabelRoomFont = myFont;                   
                    index++;
                    ShowCreateRoomProgress(new ThreadData() { ucroom = uc, column = col, floor = f, index = index, maxFloorCnt = maxFloorCnt, rooms = roomCount });
                    col++;
                }
            }

                 
        }

        /// <summary>
        /// 建立房态更新线程
        /// </summary>
        private void CreateThreadUpdateRoomStatus()
        {
            try
            {
                int i = 0;
                var roomCount = AllRoom.Count;
               
                using (var l_context = MyDataContext.GetDataContext)
                {
                    var listroom = (from q in l_context.ROOM
                                    select new
                                    {
                                        q.ID,
                                        q.ZT,
                                        q.RZBZ
                                    }).ToList();
                    var l_room = listroom.FirstOrDefault();
                    if (l_room == null)
                        return;
                    foreach (var item in AllRoom)
                    {
                        //l_context.Refresh(System.Data.Objects.RefreshMode.StoreWins, item.Value.Room);
                        l_room = listroom.First(p => p.ID == item.Value.Room.ID);
                        item.Value.Room.ZT = l_room.ZT;
                        item.Value.Room.RZBZ = l_room.RZBZ;                        
                        i++;
                        ShowUpdateRoomStatusProgress(new ThreadData() { ucroom = item.Value, index = i, rooms = roomCount });
                    }
                }
            }
            catch
            {
                return;
            }
        }

        private void ShowUpdateRoomStatusProgress(ThreadData data)
        {
            if (this.InvokeRequired)
            {
                Action<ThreadData> ac = (p1) => ShowUpdateRoomStatusProgress(p1);
                this.Invoke(ac, new object[] { data });
            }
            else
            {
                try
                {
                    if (!progressBar2.Visible)
                    {
                        progressBar2.Maximum = data.rooms;
                        progressBar2.Visible = true;
                    }
                    progressBar2.Value = data.index;
                    data.ucroom.RefreshRoom();
                    if (progressBar2.Value >= progressBar2.Maximum)
                    {
                        progressBar2.Visible = false;
                    }
                }
                catch (Exception ex )
                {
                    MessageBox.Show(ex.Message);
                    var log = Log.Instance;
                    log.Abstract = LogAbstractEnum.未知;
                    log.Message = "ShowUpdateRoomStatusProgress：" + ex.Message;
                    log.Error(ex);
                }
            }
        }
        /// <summary>
        /// 创建房间线程数据通信类
        /// </summary>
        private class ThreadData
        {
            public ucRoom ucroom { get; set; }
            /// <summary>
            /// 当前房间索引序号
            /// </summary>
            public int index { get; set; }
            /// <summary>
            /// 总房间数
            /// </summary>
            public int rooms { get; set; }
            /// <summary>
            /// 当前列
            /// </summary>
            public int column { get; set; }
            /// <summary>
            /// 当前楼层
            /// </summary>
            public int floor { get; set; }
            public int maxFloorCnt { get; set; }
        }
    }
}
